﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gencode.SQLWizz.DataType;

namespace Gencode.SQLWizz.Database
{
	class WZUpdateDatabase : WZDatabase
	{
		public WZUpdateDatabase(LogonData logData) :
			base(logData, "root/upgrade/file","upd.gc")
		{

		}

		/// <summary>
		/// starting method of thread
		/// </summary>
		public void UpdateDatabase()
		{
			Gencode.Common.SQL.DatabaseConection.ODBCConnetionString = "DSN=" + logData.ODBC + ";UID=" + logData.User + ";PWD=" + logData.Password + ";Database=" + logData.Database;
			Gencode.Common.SQL.DatabaseConection.ODBCConnection = new System.Data.Odbc.OdbcConnection(Gencode.Common.SQL.DatabaseConection.ODBCConnetionString);
			UpdateFilelist();
			bool tmp = true;
			int index = 0;
			while (tmp)
			{
				tmp = ExecuteSqlFiles(index);
				index++;

				if (!ErrorSucces)
				{
					tmp = false;
				}
			}

			ExecuteFinishEvent();
		}

		string version;
		private string DBVersion
		{
			get
			{
				if (string.IsNullOrEmpty(version))
				{
					System.Data.DataView dv = Gencode.Common.SQL.SimpleQuerry.ExecuteForDataView(
						"select Version from PrsVerwaltung where VerwaltungID = (select MAX(VerwaltungID) from PrsVerwaltung)");
					try
					{
						version = dv[0][0].ToString();
					}
					catch { }
				}
				return version;
			}
		}

		protected void UpdateFilelist()
		{
			int i=0;
			while (i < sqlFilenames.Count)
			{
				bool fileOK = true;
				try
				{
                    //check if version exists (max version in db)
					if (sqlFileVersions[sqlFilenames[i]].CompareTo(DBVersion) == 0)
						fileOK = false;

					if (fileOK)
					{
						Version dbv = new Version(DBVersion);
						Version fv = new Version(sqlFileVersions[sqlFilenames[i]]);
						//bool tmpb = true;
						if (dbv >= fv)
						{
							fileOK = false;
						}


						//string[] fileVers = sqlFileVersions[sqlFilenames[i]].Split('.');
						//string[] dbVers = DBVersion.Split('.');

						////check if version is smaller
						//for (int b = 0; b < fileVers.Length; b++)
						//{
						//    if (int.Parse(fileVers[b]) < int.Parse(dbVers[b]))
						//    {
						//        b = fileVers.Length;
						//        fileOK = false;
						//    }
						//}
					}
				}
				catch { }

				if (!fileOK)
				{
					sqlFileVersions.Remove(sqlFilenames[i]);
					sqlFilenames.RemoveAt(i);
					i--;
				}
				i++;
			}
		}
	}
}
